package org.dbstar.scheduler.beans;

import java.io.Serializable;

import org.dbstar.scheduler.control.JobController;
import org.dbstar.scheduler.control.exception.DaoException;

import net.sf.json.JSONObject;


/**
 * Job的执行结果
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-3-21
 */
public abstract class JobResult implements Serializable, Cloneable {
	private static final long serialVersionUID = -5885039564372906805L;

	private String errorException;

	/**
	 * 获得Job执行异常信息
	 * 
	 * @return Job执行异常信息
	 */
	public final String getErrorException() {
		return errorException;
	}

	public final void setErrorException(String errorException) {
		this.errorException = errorException;
	}

	/**
	 * 返回结果的字符串形式
	 * 
	 * @return 结果的字符串形式
	 */
	public final String toResultString() {
		JSONObject object = new JSONObject();
		write(object);
		return object.toString();
	}

	/**
	 * 从结果字符串中恢复
	 * 
	 * @param result 结果字符串
	 */
	public final void fromResultString(String result) {
		JSONObject object = JSONObject.fromObject(result);
		read(object);
	}

	protected void write(JSONObject object) {
		if (errorException != null) {
			object.element("errorException", errorException);
		}
	}

	protected void read(JSONObject object) {
		errorException = object.optString("errorException", null);
	}

	@Override
	public JobResult clone() throws CloneNotSupportedException {
		return (JobResult) super.clone();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((errorException == null) ? 0 : errorException.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		JobResult other = (JobResult) obj;
		if (errorException == null) {
			if (other.errorException != null)
				return false;
		} else if (!errorException.equals(other.errorException))
			return false;
		return true;
	}

	public abstract void init(Job job, JobController jobController) throws DaoException;

	/**
	 * 判定任务执行结果是否为成功。
	 * 
	 * @return true-执行结果为成功;false-不成功
	 */
	public abstract boolean isSucceed();

	public void reExecute(Job job, boolean failedOnly, JobController jobController) throws DaoException {
		setErrorException(null);
	}
}
